<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/2/11
 * Time: 11:19
 */

namespace app\base\service;

use Wechat;

class WechatPay
{
    public function makeWeChatPay($description, $title, $orderno, $money, $attach='deposit')
    {
        $noticeUrl   = "http://new.jjcxfw.com/api/Notify/wechat";
        $input       = new Wechat\WxPayUnifiedOrder();
        $description = mb_substr($description, 0, 20, 'utf-8');
        $title       = mb_substr($title, 0, 10, 'utf-8');
        $input->SetBody($description);
        $input->SetAttach($attach);
        $input->SetOut_trade_no($orderno);
        $input->SetTotal_fee($money);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag($title);
        $input->SetNotify_url($noticeUrl);
        $input->SetTrade_type("APP");
        $UnifiedOrderResult = Wechat\WxPayApi::unifiedOrder($input);
        //二次加签
        if (!array_key_exists("appid", $UnifiedOrderResult)
            || !array_key_exists("prepay_id", $UnifiedOrderResult)
            || $UnifiedOrderResult['prepay_id'] == "") {
            $errMsg = empty($UnifiedOrderResult['return_msg']) ? '微信统一下单失败！' : $UnifiedOrderResult['return_msg'];
            $errMsg = $errMsg=='OK' ? $UnifiedOrderResult['err_code_des'] :$errMsg;
            $errMsg = preg_replace('/^\d+/', '', $errMsg);
            trace($errMsg,'wxPay');
            return [0,$errMsg];
        } else {
            $params = array(
                'appid'     => $UnifiedOrderResult['appid'],
                'partnerid' => $UnifiedOrderResult['mch_id'],
                'prepayid'  => $UnifiedOrderResult['prepay_id'],
                'package'   => 'Sign=WXPay',
                'noncestr'  => Wechat\WxPayApi::getNonceStr(),
                'timestamp' => time(),
            );
            // 拼装数据进行签名
            $params['sign'] = $this->SetSign($params);   // 获取签名
            if ($params['sign']) {
                return [1,$params];
            } else {
                trace('缺少sign值！','wxPay');
                return [0,'缺少sign值！'];
            }
        }
    }

    /**
     * 签名
     * @param $params
     * @return string
     */
    public function SetSign($params)
    {
        $key = config('base.WXKEY');
        //签名步骤一：按字典序排序参数
        ksort($params);
        $buff = "";
        foreach ($params as $k => $v) {
            if ($k != "sign" && $v != "" && !is_array($v)) {
                $buff .= $k . "=" . $v . "&";
            }
        }
        $string = trim($buff, "&");
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . $key;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $sign = strtoupper($string);
        return $sign;
    }
}